package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDto;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String KEY_PREFIX = "ly_user_verify:";
    private StringRedisTemplate redisTemplate;

    private AmqpTemplate amqpTemplate;

    @Autowired
    PasswordEncoder passwordEncoder;

    public UserServiceImpl(StringRedisTemplate redisTemplate, AmqpTemplate amqpTemplate) {
        this.redisTemplate = redisTemplate;
        this.amqpTemplate = amqpTemplate;
    }

    @Override
    public Boolean exists(String data, Integer type) {
        if(type ==1){
            int username = this.query().eq("username", data).list().size();
            return username==1;
        }else if(type ==2){
            int phone = this.query().eq("phone", data).list().size();
            return phone==1;
        }else
        return false;
    }

    @Override
    public UserDto queryByNameAndPd(String username, String password) {
        // 1.根据用户名查询
//        User user = getOne(new QueryWrapper<User>().eq("username", username));
        User user = query().eq("username", username).one();
        // 2.判断是否存在
        if (user == null) {
            // 用户名错误
            throw new LyException(400, "用户名或密码错误");
        }

        // 3.校验密码
        if(!passwordEncoder.matches(password, user.getPassword())){
            // 密码错误
            throw new LyException(400, "用户名或密码错误");
        }
        // 4.转换DTO
        return new UserDto(user);
    }

    @Override
    public void saveUser(User user,String code) {
        String key_prefix = redisTemplate.opsForValue().get(KEY_PREFIX+user.getPhone());

        if(!StringUtils.equals(code, key_prefix)){
            throw new LyException(400,"验证码错误");
        }
        // 2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);
    }

    @Override
    public void sendCode(String phone) {
        // 2.使用Apache的工具类生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        // 4.发送RabbitMQ消息到ly-sms
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public UserDetail checkLogin(String token) {

        Payload payload = jwtUtils.parseJwt(token);

        return payload.getUserDetail();
    }
}